package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.ApThreadLocalUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    /**
     * ES文章分页搜索
     *
     * @param userSearchDto
     * @return
     */
    @Autowired
    RestHighLevelClient client;

    @Autowired
    ApUserSearchService apUserSearchService;
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //调用保存历史记录方法
        if (dto.getSearchWords()!=null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Integer userId = ApThreadLocalUtil.getUser().getId();
     if (userId != null) {
         apUserSearchService.insert(dto.getSearchWords(),userId);
     }


        SearchRequest searchRequest=new SearchRequest("app_info_article");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //关键字查询
        if (dto.getSearchWords()!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",dto.getSearchWords()));
        }
        //小于最小时间
        if (dto.getMinBehotTime() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }
        searchRequest.source().query(boolQueryBuilder);
        //分页
        searchRequest.source().from(0).size(dto.getPageSize());
        //排序
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        //高亮
        HighlightBuilder highlight=new HighlightBuilder();
        highlight.field("title");
        highlight.requireFieldMatch(false);
        highlight.preTags("<font style='color: red; font-size: inherit;'>");
        highlight.postTags("</font>");
        searchRequest.source().highlighter(highlight);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        return result(response);
    }

    private ResponseResult result(SearchResponse response) {
        ArrayList<Map> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, Object> map = hit.getSourceAsMap();
            //高亮数据封装
            //如果高亮域中有值
            if (hit.getHighlightFields().size()>0){
                Text[] titles = hit.getHighlightFields().get("title").fragments();
                if (titles != null) {
                    //把高亮之后的h_tile=<font>测试</font>
                    map.put("h_title",titles[0].toString());
                }else {
                    //表示没有高亮域，我们则把h_title=测试
                    map.put("h_title",map.get("title"));
                }
                list.add(map);
            }
        }

        return ResponseResult.okResult(list);
    }
}
